import { defineStore } from 'pinia'

export const useProjectStore = defineStore('project', {
  state: () => ({
    // 工作目录
    workspaceDir: null,
    // 项目列表（从最近项目和本地加载）
    projects: [],
    // 当前选中的项目
    project: null,
    // 当前项目的图像列表
    images: [],
    // 当前正在处理的图像
    currentImage: null,
    currentImgId: 0,
    // 项目名称（向后兼容）
    projectName: '深度学习标注',
    // 图像信息（向后兼容）
    imageInfo: null
  }),
  
  getters: {
    // 向后兼容的getters
    getProjects: (state) => state.projects,
    getProject: (state) => state.project,
    getImages: (state) => state.project?.images || state.images || [],
    getImageInfo: (state) => state.imageInfo,
    getCurrentImgId: (state) => state.currentImgId,
    
    // 新的getters
    isProjectLoaded: (state) => !!state.project,
    annotatedImages: (state) => {
      const images = state.project?.images || state.images || []
      return images.filter(img => img.annotated || img.is_annotated)
    },
    projectProgress: (state) => {
      const images = state.project?.images || state.images || []
      if (images.length === 0) return 0
      const annotated = images.filter(img => img.annotated || img.is_annotated).length
      return Math.round((annotated / images.length) * 100)
    }
  },
  
  actions: {
    // === 工作目录管理 ===
    
    /**
     * 设置工作目录并初始化项目管理器
     */
    async setWorkspaceDir(dir) {
      this.workspaceDir = dir
      if (window.electronAPI?.initializeProjectManager) {
        const result = await window.electronAPI.initializeProjectManager(dir)
        if (result.success) {
          console.log('[Store] 项目管理器初始化成功')
          await this.loadRecentProjects()
        } else {
          console.error('[Store] 项目管理器初始化失败:', result.error)
        }
      }
    },
    
    // === 项目管理 ===
    
    /**
     * 加载最近项目列表
     */
    async loadRecentProjects() {
      if (window.electronAPI?.getRecentProjects) {
        const result = await window.electronAPI.getRecentProjects()
        if (result.success) {
          this.projects = result.projects || []
          console.log('[Store] 加载最近项目:', this.projects.length, '个')
        }
      }
    },
    
    /**
     * 创建新项目
     */
    async createProject(projectData) {
      if (!this.workspaceDir) {
        throw new Error('请先选择工作目录')
      }
      
      if (window.electronAPI?.createProject) {
        try {
          // 确保数据是可序列化的，避免IPC克隆问题
          const cleanProjectData = JSON.parse(JSON.stringify(projectData))
          
          const result = await window.electronAPI.createProject(cleanProjectData)
          
          if (result.success) {
            // 确保新创建的项目有正确的状态字段
            const newProject = {
              ...result.project,
              exists: true,
              status: 'available'
            }
            
            // 添加到项目列表
            this.projects.unshift(newProject)
            // 设置为当前项目
            this.setProject(newProject)
            console.log('[Store] 项目创建成功:', result.project.project?.name)
            return result
          } else {
            throw new Error(result.error || '创建项目失败')
          }
        } catch (error) {
          console.error('[Store] 创建项目时出错:', error)
          throw error
        }
      }
      throw new Error('项目管理API不可用')
    },
    
    /**
     * 加载项目
     */
    async loadProject(projectPath) {
      if (window.electronAPI?.loadProject) {
        const result = await window.electronAPI.loadProject(projectPath)
        if (result.success) {
          // 确保加载的项目有正确的状态字段
          const loadedProject = {
            ...result.project,
            exists: true,
            status: 'available'
          }
          this.setProject(loadedProject)
          console.log('[Store] 项目加载成功:', result.project.project?.name)
          return result
        } else {
          throw new Error(result.error || '加载项目失败')
        }
      }
      throw new Error('项目管理API不可用')
    },
    
    /**
     * 保存当前项目
     */
    async saveProject() {
      if (!this.project) {
        throw new Error('没有项目需要保存')
      }
      
      if (window.electronAPI?.saveProject) {
        // 序列化项目数据以避免IPC克隆问题
        const cleanProjectData = JSON.parse(JSON.stringify(this.project))
        const result = await window.electronAPI.saveProject(cleanProjectData)
        if (result.success) {
          console.log('[Store] 项目保存成功')
          return result
        } else {
          throw new Error(result.error || '保存项目失败')
        }
      }
      throw new Error('项目管理API不可用')
    },
    
    // === 向后兼容的项目管理方法 ===
    
    addProject(item) {
      this.projects = [item, ...this.projects]
    },
    
    setProject(item) {
      // 处理null值的情况
      if (!item) {
        this.project = null
        this.images = []
        return
      }
      
      const cId = item.id || item.project?.id
      // 检测是否在项目列表，如果在的话是编辑修改列表数据
      const index = this.projects.findIndex(({ id, project }) => 
        (id || project?.id) == cId
      )
      if (index > -1) {
        this.projects[index] = item
      }
      this.project = { ...item }
      
      // 同步图像列表
      if (item.images) {
        this.images = item.images
      }
    },
    
    // === 图像管理 ===
    
    /**
     * 设置图像列表
     */
    setImages(filePaths) {
      this.images = filePaths.map(p => ({
        name: p.split(/[\\/]/).pop(),
        path: p,
        annotated: false
      }))
      
      // 如果有当前项目，同步到项目中
      if (this.project) {
        this.project.images = [...this.images]
      }
    },
    
    /**
     * 清空图像列表
     */
    clearImages() {
      this.images = []
      this.currentImage = null
      
      if (this.project) {
        this.project.images = []
      }
    },
    
    /**
     * 设置当前图像
     */
    setCurrentImage(imagePath) {
      this.currentImage = imagePath
    },
    
    /**
     * 标记图像为已标注
     */
    markAsAnnotated(imagePath) {
      // 更新本地图像列表
      const image = this.images.find(img => img.path === imagePath)
      if (image) {
        image.annotated = true
      }
      
      // 更新项目中的图像列表
      if (this.project?.images) {
        const projectImage = this.project.images.find(img => img.path === imagePath)
        if (projectImage) {
          projectImage.annotated = true
          projectImage.is_annotated = true
        }
      }
    },
    
    /**
     * 导入图像到当前项目
     */
    async importImagesToProject(imagePaths) {
      if (!this.project?.path) {
        throw new Error('没有项目或项目路径无效')
      }
      
      if (window.electronAPI?.importImagesToProject) {
        const result = await window.electronAPI.importImagesToProject(
          this.project.path, 
          imagePaths
        )
        
        if (result.success) {
          // 更新项目图像列表
          if (!this.project.images) {
            this.project.images = []
          }
          
          // 转换格式以保持兼容性
          const formattedImages = result.images.map(img => ({
            id: img.id,
            name: img.filename,
            path: img.path,
            annotated: img.is_annotated,
            is_annotated: img.is_annotated,
            ...img
          }))
          
          this.project.images = [...this.project.images, ...formattedImages]
          this.images = [...this.images, ...formattedImages]
          
          console.log('[Store] 图像导入成功:', result.imported, '张')
          return result
        } else {
          throw new Error(result.error || '导入图像失败')
        }
      }
      throw new Error('项目管理API不可用')
    },
    
    // === 向后兼容的方法 ===
    
    addImage(item) {
      if (!this.project.images) {
        this.project.images = []
      }
      
      // 检查是否已存在相同图像（基于ID和路径）
      const existingImage = this.project.images.find(img => 
        img.id === item.id || img.path === item.path
      )
      
      if (!existingImage) {
        this.project.images.unshift(item)
        this.images.unshift(item)
        console.log(`[Store] 添加新图像: ${item.name}`)
      } else {
        console.log(`[Store] 跳过重复图像: ${item.name}`)
      }
    },
    
    setImageInfo(item) {
      const cId = this.project?.id || this.project?.project?.id
      // 检测是否在项目列表，如果在的话是编辑修改列表数据
      const index = this.projects.findIndex(({ id, project }) => 
        (id || project?.id) == cId
      )
      if (index > -1) {
        const { images } = this.projects[index]
        if (images) {
          const i = images.findIndex(({ id: zid }) => zid == item.id)
          if (i > -1) {
            this.projects[index].images[i] = item
          }
        }
      }
      this.imageInfo = item
    },
    
    setCurrentImg(id) {
      this.currentImgId = id
    }
  }
})